package com.example.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.user.common.BaseResponse;
import com.example.user.common.ErrorCode;
import com.example.user.common.ResultUtil;
import com.example.user.mapper.UserMapper;
import com.example.user.model.User;
import com.example.user.model.request.UserLoginRequest;
import com.example.user.model.request.UserRegisterRequest;
import com.example.user.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.user.contant.UserContant.IS_ADMIN;
import static com.example.user.contant.UserContant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if(userRegisterRequest == null) return ResultUtil.error(ErrorCode.PARAMS_ERROR);

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtil.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest , HttpServletRequest request) {
        if(userLoginRequest == null) return ResultUtil.error(ErrorCode.PARAMS_ERROR);

        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtil.success(user);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> seachUsers(String userName , HttpServletRequest request){
        if(isAdmin(request)) return ResultUtil.success(new ArrayList<>());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if(!StringUtils.isAllBlank(userName)){
            queryWrapper.like("user_name", userName);
        }

        List<User> users = userMapper.selectList(queryWrapper);
        List<User> collect = users.stream().map(item -> userService.toSafeUser(item)).collect(Collectors.toList());
        return ResultUtil.success(collect);
    };

    @GetMapping("/delete")
    public BaseResponse<Integer> deleteUser(@RequestParam Long id , HttpServletRequest request){
        if(isAdmin(request))  return new  BaseResponse<>(0 , 0 , "ok");
        if(id <= 0)  return new  BaseResponse<>(0 , 0 , "ok");
        int i = userMapper.deleteById(id);
        return new  BaseResponse<>(0 , i , "ok");
    }


    /**
     * 用户注销
     * @param request
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> logout(HttpServletRequest request){
        if(request == null) return null;
        int logout = userService.logout(request);
        return ResultUtil.success(logout);

    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser (HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) obj;
        if(currentUser == null) return ResultUtil.success(null);
        Long userId = currentUser.getId();
        User user = userMapper.selectById(userId);
        User safeUser = userService.toSafeUser(user);
        return ResultUtil.success(safeUser);
    }


    private Boolean isAdmin(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User)userObj;
        return user !=  null && user.getUser_role() == IS_ADMIN;
    };

}
